import { Injectable } from '@nestjs/common';
import { QueryOnlineDto } from './dto/query-online.dto';
import { RedisService } from 'src/db/redis-cache.service';

@Injectable()
export class OnlineService {
  constructor(private readonly redisService: RedisService) {}
  /**
   * 获取所有在线用户
   * @returns
   */
  async findAll(query: QueryOnlineDto) {
    const keys = await this.redisService.keys('login_token:*');
    const values = await this.redisService.mget(keys);
    // 处理分页
    if (!query.pageNum || query.pageNum < 1) {
      query.pageNum = 1;
    }
    if (!query.pageSize || query.pageSize < 1) {
      query.pageSize = 10;
    }
    const res = values
      .map((item) => {
        return {
          browser: item.ua.browser.name + ' ' + item.ua.browser.major,
          ip: item.ip,
          loginLocation: item.ipAddress,
          loginTime: item.loginTime,
          os: item.ua.os.name + ' ' + item.ua.os.version,
          userName: item.user.username,
          token_id: item.token_id,
          token: item.token
        };
      })
      .filter(
        (k) =>
        query.username ? k.userName.includes(query.username) : true &&
        query.address ? k.loginLocation.includes(query.address) : true
      )
      .slice(
        (query.pageNum - 1) * query.pageSize,
        query.pageNum * query.pageSize,
      ).sort((a,b) => b.loginTime - a.loginTime)
    return {
      list:res,
      total:res.length || 0,
      current: query.pageNum
    };
  }

  /**
   * 强制退出
   * @param token 
   * @returns 
   */
  async remove(token: string) {
    await this.redisService.del(`login_token:${token}`);
    return {
      data:token
    };
  }
}
